#include "preHeader.h"
#include "MapTeamManager.h"
#include "Map/MapInstance.h"
#include "Session/GameServerMgr.h"

static inline uint64 MakeTeamKey(uint16 gsId, uint32 teamId) {
	return ((uint64)gsId << 32) + teamId;
}

MapTeamManager::MapTeamManager(MapInstance* pMapInstance)
: m_pMapInstance(pMapInstance)
{
}

MapTeamManager::~MapTeamManager()
{
	for (auto& pair : m_allTeams) {
		delete pair.second;
	}
}

void MapTeamManager::LoadTeamFromGSPacket(INetPacket& pack, uint16 gsId)
{
	uint32 teamId = pack.Read<uint32>();
	auto pTeam = CreateAndGetTeam(gsId, teamId);
	pTeam->LoadTeamFromGSPacket(pack);
}

void MapTeamManager::DeleteTeam(uint16 gsId, uint32 teamId)
{
	auto itr = m_allTeams.find(MakeTeamKey(gsId, teamId));
	if (itr != m_allTeams.end()) {
		auto pTeam = itr->second;
		m_allTeams.erase(itr);
		delete pTeam;
	}
}

void MapTeamManager::SetTeamOrPullTeam(Player* pPlayer, uint32 teamId)
{
	auto pTeam = GetTeam(pPlayer->GetGsId(), teamId);
	if (pTeam != NULL) {
		pPlayer->SetTeam(pTeam);
		return;
	}

	NetPacket pack(MS_MAP_TEAM_CREATE);
	pack << m_pMapInstance->getInstGuid() << teamId;
	pPlayer->SendPacket2Gs(pack);
}

MapTeam* MapTeamManager::CreateAndGetTeam(uint16 gsId, uint32 teamId)
{
	auto pTeam = GetTeam(gsId, teamId);
	if (pTeam == NULL) {
		pTeam = new MapTeam(m_pMapInstance, gsId, teamId);
		m_allTeams.emplace(MakeTeamKey(gsId, teamId), pTeam);
	}
	return pTeam;
}

MapTeam* MapTeamManager::GetTeam(uint16 gsId, uint32 teamId) const
{
	auto itr = m_allTeams.find(MakeTeamKey(gsId, teamId));
	return itr != m_allTeams.end() ? itr->second : NULL;
}
